import { Uri, window } from "vscode";
import { readFile, createFile } from "../utils/system";
import { isJSONString } from "../utils/rule";

const interfaceDefinition = require("json-to-ts-interface");

export const jsonChangeInterface = async (uri: Uri) => {
  // 获取编辑器对象
  const editor = window.activeTextEditor;
  if (!editor) {
    return;
  }
  const doc = editor.document;

  if (doc.isDirty) {
    return window.showInformationMessage("文件尚未保存。", { modal: true });
  }

  const dirPath = uri.fsPath;

  const selection = editor.selection;
  const words = doc.getText(selection);

  if (!isJSONString(words)) {
    return window.showInformationMessage("select is not JSON", {
      modal: true,
    });
  }

  const file = await readFile(dirPath);
  const mainArray = file.split("\n");
  const subArray = words.split("\n");
  const interfaceList = interfaceDefinition(words).split("\n");

  let index = arrayContainsArray(mainArray, subArray);
  mainArray.splice(index, subArray.length, ...interfaceList);

  createFile(dirPath, mainArray.join("\n"));
};

// 查找所选内容的行数
const arrayContainsArray = (mainArray: string[], subArray: string[]) => {
  for (let i = 0; i <= mainArray.length - subArray.length; i++) {
    let match = true;
    for (let j = 0; j < subArray.length; j++) {
      if (mainArray[i + j] !== subArray[j]) {
        match = false;
        break;
      }
    }
    if (match) {
      return i;
    }
  }
  return -1; // 表示未找到子数组
};
